using System;
using System.ComponentModel;
using System.ComponentModel.Design.Serialization;
using System.Reflection;
using System.Globalization;

namespace Camalon.Drawing
{
	public class RectangleMarginsConverter:ExpandableInstanceConverter
	{

		public override object ConvertFrom(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value)
		{
			if ( value is string )
			{
				
				string sVal = (string)value;
				if( sVal.Length == 0) return RectangleMargins.Empty;
				//if( sVal.ToLower().IndexOf("null") != -1) return null;
				if( sVal.ToLower().IndexOf("empty") != -1) return RectangleMargins.Empty;

				string[] args		= sVal.Split(';');

				string   sleft		= args[0];
				int	 left			= int.Parse(sleft);    
				string   sright		= args[1];
				int	 right			= int.Parse(sright);;    
				string	 stop		= args[2];
				int	 top			= int.Parse(stop);;    
				string   sbottom	= args[3];
				int	 bottom			= int.Parse(sbottom);;    				


				return new RectangleMargins(left,right,top, bottom);

			}

			return base.ConvertFrom (context, culture, value);
		}


		public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destinationType)
		{
			if (destinationType == typeof(string)) 
			{
				RectangleMargins m = (RectangleMargins)value;
				if( m.IsEmpty) return "Empty";

				return string.Format("{0};{1};{2};{3}", m.Left ,m.Right, m.Top, m.Bottom );
			}

			if (destinationType == typeof(InstanceDescriptor) && value is RectangleMargins) 
			{
				RectangleMargins m = (RectangleMargins)value;
				ConstructorInfo ctor = typeof(RectangleMargins).GetConstructor(new Type[] {typeof(int), typeof(int), typeof(int),typeof(int)});
				if (ctor != null) return new InstanceDescriptor(ctor, new object[] {m.Left,m.Right,m.Top, m.Bottom});
				else throw base.GetConvertToException( m, typeof(RectangleMargins) );
			}

			return base.ConvertTo (context, culture, value, destinationType);
		}

	}

}
